package com.example.databasepj.service;

import com.example.databasepj.Request.ReserveRequest;
import com.example.databasepj.dto.MessageData;
import com.example.databasepj.entity.MerchantEntity;
import com.example.databasepj.entity.MessageEntity;
import com.example.databasepj.exception.BusinessException;
import com.example.databasepj.exception.ErrorCode;
import com.example.databasepj.mapper.MerchantMapper;
import com.example.databasepj.mapper.MessageMapper;
import org.apache.ibatis.exceptions.PersistenceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class MessageService {
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private MerchantMapper merchantMapper;

    //创建新消息
    public void insertReserveMessage(ReserveRequest reserveRequest){
        //先创建message
        MessageEntity messageEntity=new MessageEntity(reserveRequest.getUser_ID(), reserveRequest.getMerchant_ID());
        messageEntity.setMessage_type(0);//预定消息
        LocalDateTime now = LocalDateTime.now();
        messageEntity.setTime(now);
        MerchantEntity merchant = merchantMapper.selectMerchantById(reserveRequest.getMerchant_ID());
        messageEntity.setMessage_content("您已成功预约！您的预约信息如下：\n 时间："+reserveRequest.getReserve_time()+"\n商家："+merchant.getMerchant_name()+"\n地址:"+merchant.getAddress());

        try {
            messageMapper.insertMessage(messageEntity);
            // 插入成功后的逻辑
        } catch (PersistenceException e) {
            // 记录异常信息
//            ex.printStackTrace();
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);

        }
    }
    //user获取消息列表
    public List<MessageData> getMessageList(int userId){
        List<MessageEntity> messageEntities = messageMapper.selectMessageByUserId(userId);
        List<MessageData> results=new ArrayList<>();
        for(int i=0;i<messageEntities.size();i++){
            MessageEntity message=messageEntities.get(i);
            MessageData messageData = new MessageData(message.getMessage_id(), message.getMerchant_id(), message.getMessage_type(), message.getMessage_content(), message.getTime());
            results.add(messageData);
        }
        return results;
    }
}
